package com.util.annotate.demo.service;




import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * 动态代理具体实现方法
 */
public class PropertyInvocationHandler implements InvocationHandler {
    private Properties properties;

    public PropertyInvocationHandler(Properties properties) {
        this.properties = properties;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(" 调用 method = [" + method.getName() +"]");
        ReadConf readConf = method.getAnnotation(ReadConf.class);
        if (readConf == null){
            return null;
        }
        String value = readConf.value();
        String property = properties.getProperty(value);
        if (property == null){
            return null;
        }

        Class<?> returnClass = method.getReturnType();
        // 基本原始类型，这里只写了部分类型，满足当前demo接口返回值类型，如遇项目有多重类型，可以添加补全所以类型
        if (returnClass.isPrimitive()){
            if (returnClass.equals(int.class)){
                return Integer.valueOf(property);
            }
            else if (returnClass.equals(long.class)){ return (Long.valueOf(property));}
            else if (returnClass.equals(double.class)) {return (Double.valueOf(property));}
            else if (returnClass.equals(float.class)) { return (Float.valueOf(property)); }
            else if (returnClass.equals(boolean.class)) { return (Boolean.valueOf(property));}
        }else {
            if (returnClass.equals(Integer.class)){
                return Integer.valueOf(property);
            }else if (returnClass.equals(String.class)){
                return String.valueOf(property);
            }else if (returnClass.equals(Boolean.class)){
                return Boolean.valueOf(property);
            }
        }

        return property;

    }
}
